// 考试用到的工具函数集合

// import Cookies from 'js-cookie'

/**
 * 将答案保存到 cookies 中
 * @param {String} examId 考试id
 * @param {String} qId 题目id
 * @param {String|Array} answer 作答情况，
 */
export function saveAnswerToCookies(examId, qId, answer) {
  // console.log('get answer:', qId, answer)

  // 字符串转数组
  if (typeof answer === 'string') {
    answer = [answer]
    // console.log('字符串转数组', answer)
  }

  let savedAnswers = JSON.parse(localStorage.getItem(`exam${examId}`)) || []
  // console.log('savedAnswers', savedAnswers)
  let found = false
  for (let i = 0; i < savedAnswers.length; i++) {
    // 若存在则更新
    if (savedAnswers[i].qId === qId) {
      savedAnswers[i].answer = answer
      console.log('answer changed to:', savedAnswers)
      found = true
      break
    }
  }
  const ans = { qId: qId, answer: answer }
  if (!found) {
    // 若不存在则新增
    if (savedAnswers.length === 0) savedAnswers = [ans]
    else savedAnswers.push(ans)
    console.log('new answer! now count:', savedAnswers.length)
  }

  // 存入 Cookies
  // Cookies.set('exam' + examId, savedAnswers)
  localStorage.setItem('exam' + examId, JSON.stringify(savedAnswers))
  console.log('answer saved with async & cookies.')
}

/**
 * 获取cookies中的作答情况
 * 异步函数！！！
 * @param {String} examId 考试id
 */
export function getAnswersByExamId(examId) {
  return new Promise((resolve, reject) => {
    // 异步返回，等最后的答案存好了之后再提交
    setTimeout(() => {
      console.log('getAnswersByExamId', examId)
      const savedAnswers =
        JSON.parse(localStorage.getItem(`exam${examId}`)) || []
      resolve(savedAnswers)
    }, 500)
  })
}

/**
 * 获取cookies中的作答情况
 * 异步函数！！！
 * @param {String} examId 考试id
 */
export function getAnswerJSONByExamId(examId) {
  return new Promise((resolve, reject) => {
    // 异步返回，等最后的答案存好了之后再提交
    setTimeout(() => {
      console.log('getAnswersByExamId', examId)
      const savedAnswers = localStorage.getItem(`exam${examId}`)
      if (savedAnswers) resolve(savedAnswers)
      else reject('不能交白卷！')
    }, 500)
  })
}

export function clearAnswerExamId(examId) {
  console.log('clearAnswerExamId', examId)
  // localStorage.setItem(`exam${examId}`, [])
  localStorage.removeItem(`exam${examId}`)
}
